<script setup lang="ts">
import { has } from 'lodash-es'
import { getCdnNodeSimpleApi } from '@/apis/modules/cdn'
import { BaseConf, DiskConf, WafConf } from './components'

const route = useRoute()
const router = useRouter()

type ModuleKeys = 'base' | 'disk' | 'waf'

const componentMap: Record<ModuleKeys, Component> = {
  base: BaseConf,
  disk: DiskConf,
  waf: WafConf,
}
const currComponent = computed(() => {
  const mod = String(route.params?.module || '')
  if (has(componentMap, mod)) {
    return componentMap[mod as ModuleKeys]
  }
  return BaseConf
})

const selectList = ref<any[]>([])
const options = ref<any[]>([])
function getNodeList() {
  getCdnNodeSimpleApi({}).then((res) => {
    selectList.value = res.list || []
    options.value = selectList.value
      .map((item: any) => ({ label: item.name, value: item.id }))
      .filter(Boolean)
  })
}

function handleSiteChange(id: string) {
  router.replace({ ...route, params: { id } })
}
onBeforeMount(() => {
  const mod = String(route.params?.module || '')
  if (!mod) {
    router.replace({
      name: 'CdnNodeNodeManagement',
      params: {
        module: 'base',
      },
    })
  }
})

const paramsId = ref<string>('')

watch(
  () => route.meta.parentName,
  () => {
    const id = (route.params.id as string) ?? ''
    if (id) {
      paramsId.value = id
    }
  },
  {
    immediate: true,
    deep: true,
  },
)

onMounted(() => {
  getNodeList()
})
</script>

<template>
  <a-select
    v-model="paramsId"
    class="node-change !w-60"
    style="position: absolute; top: 140px; right: 32px; z-index: 100"
    @change="v => handleSiteChange(v as string)"
  >
    <a-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value"
      :disabled="item.value === paramsId"
    />
  </a-select>
  <component :is="currComponent" />
</template>

<style lang="less" scoped></style>
